<?php
namespace Common\Behavior;

use Think\Behavior;

class AuthCheckBehavior extends Behavior {
	/**
	 * 用户登录后所需基本信息
	 * array(
	 * 'userName'=>'',用户名
	 * 'id'=>'',用户id
	 * 'type'=>'',普通用户类型,个人:1,机构:2(userType为user时有效)
	 * 'auth'=>'',用户权限
	 * )
	 */
	private $_userAttr = array(
		'userName',
		'id',
		'auth',
	);

	public function run(&$param){
		if(C( 'USER_AUTH_ON' )){
			// 获取用户登录信息
			$userInfo = $this->getUserInfo( 'user', $this->_userAttr );
			if(!$userInfo){
				return array(
					'success'=>false,
					'type'=>'login',
					'msg'=>'您还没有登录,请登录!',
				);
			}
			// 获取用户权限
			$auth = $userInfo['auth'];
			// 验证权限
			$auth_check = $this->checkAuth( $auth );
			if(!$auth_check){
				return array(
					'success'=>false,
					'type'=>'auth',
					'msg'=>'对不起,您没有相关操作权限!请联系管理员!',
				);
			}
			return array(
				'success'=>true,
			);
		}else{
			return array(
				'success'=>true,
			);
		}
	}

	/**
	 * 获取用户登录信息
	 * @param string $index
	 * @param array $attr
	 * @return boolean|Ambigous <mixed, NULL>
	 */
	protected function getUserInfo($index, $attr){
		if(session( "?{$index}" )){
			$arr = session( $index );
			foreach( $attr as $val ){
				if(empty( $arr[$val] )){
					if($val !== 'auth'){
						return false;
					}
				}
			}
			return $arr;
		}else{
			return false;
		}
	}

	/**
	 * 权限验证
	 * @param array $auth
	 * @return boolean
	 */
	protected function checkAuth($auth){
        if(!empty($auth['org']) && $auth['org']=='super'){
            return true;
        }
		$host = I( 'server.HTTP_HOST' );
		$suffix = C( 'URL_HTML_SUFFIX' );
		$url = I( 'server.REQUEST_URI' );
		$url = preg_replace('/\?.*$/', '', $url);
		$url = strtr($url, array(
			$host =>'',
			'.'.$suffix =>'',
		));
		$url = trim( $url, '/' );
		list( $moudle, $controller, $action ) = explode( '/', $url );
		$moudle=strtolower($moudle);
		$controller=strtolower($controller);

		$action=strtolower($action);
        if($controller=="index"){
            return true;
        }
		$auth['m']=array_map('strtolower', $auth['m']);
		$auth['c']=array_map('strtolower', $auth['c']);
		foreach ($auth['a'] as $k=>$v){
			$auth['a'][strtolower($k)]=array_map('strtolower',$v);
		}
		$auth_check=true;
		//check module
		if(!in_array($moudle, $auth['m'])){
			$auth_check=false;
		}
		//check action
		if($auth_check && !empty( $auth['a'] ) && !in_array($action, $auth['a'][$controller])){
			//check controller
//			if(empty($auth['c'])){
//				$auth_check=false;
//			}elseif(!empty( $auth['c'] ) && !in_array($controller, $auth['c'])){
//				$auth_check=false;
//			}
            $auth_check=false;
		}
		//check controller
		if($auth_check && empty($auth['a']) && !empty( $auth['c'] ) && !in_array($controller, $auth['c'])){
			$auth_check=false;
		}
		return $auth_check;
	}
}

?>